package com.bana.fvs.app.main.fragment;

import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.bana.fvs.R;
import com.bana.fvs.app.base.BaseFragment;
import com.bana.fvs.app.common.ConstantsField;
import com.bana.fvs.app.main.adapter.MyAdapter;
import com.bana.fvs.app.main.entity.FogZoneListItemBean;
import com.bana.fvs.app.main.view.CommonHeadRefreshView;
import com.bana.fvs.app.main.view.MyItemDecoration;
import com.bana.fvs.app.module.detaile.EquipmentDetailActivity;
import com.bana.fvs.app.module.detaile.entity.VisibilityControllerDetailBean;
import com.bana.fvs.app.module.tab2.entity.PushVisibilityBean;
import com.bana.fvs.app.module.tab2.tab2Detail.entity.EquipListItemBean;
import com.bana.fvs.app.mvp.ConstantsValue;
import com.bana.fvs.app.mvp.contract.FogZoneContract;
import com.bana.fvs.app.mvp.presenter.FogZonePresenter;
import com.bana.fvs.app.other.xrecyclerview.ProgressStyle;
import com.bana.fvs.app.other.xrecyclerview.XRecyclerView;
import com.bana.fvs.app.util.CommonUtils;
import com.bana.fvs.app.util.TimeUtils;
import com.bana.fvs.app.util.UserInfoUtils;
import com.google.gson.Gson;
import com.wei.commonlibrary.manager.RxBus;
import com.wei.commonlibrary.net.CommException;
import com.wei.commonlibrary.utils.GlobalContext;
import com.wei.commonlibrary.utils.SPUtils;
import com.wei.commonlibrary.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;

/**
 * Author : yanftch
 * Date : 2018/2/7
 * Time : 10:27
 * Desc : 雾区监测Fragment
 */
// TODO: 2018/3/11   注释掉的制造假数据的代码先留着吧
// TODO: 2018/3/11 点击跳转，传递的内容还没处理

public class FogZoneFragment extends BaseFragment<FogZonePresenter> implements FogZoneContract.AbsFogZoneView {
    private static final String TAG = "dah_FogZoneFragment";
    private CommonHeadRefreshView mCommonHeadRefreshView;
    private XRecyclerView mXRecyclerView;
    private List<FogZoneListItemBean> datas;
    private MyAdapter mAdapter;
    private MyItemDecoration myItemDecoration;

    private LinearLayoutManager layoutManager;

    @Override
    protected void initView(View rootView) {
        myItemDecoration = new MyItemDecoration();
        View view = rootView.findViewById(R.id.commonHeadViewId);
        mCommonHeadRefreshView = new CommonHeadRefreshView(mContext, view, "");
        mXRecyclerView = rootView.findViewById(R.id.fogZoneListView);
        datas = new ArrayList<>();
//        for (int i = 0; i < 20; i++) {
//            FogZoneListItemBean bean = new FogZoneListItemBean();
//            bean.setWqbm(i + "");
//            bean.setGxsj("2011-11-11 11:12---" + i);
//            bean.setWqmc("长江路雾区" + i);
//            bean.setNjddj(i + "");
//            bean.setNjd(i);
//            bean.setWqtq("良好" + i);
//            datas.add(bean);
//        }
        mAdapter = new MyAdapter(datas);

        layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mXRecyclerView.setLayoutManager(layoutManager);
        mXRecyclerView.setPullRefreshEnabled(false);//下拉刷新-不可以
        mXRecyclerView.setLoadingMoreEnabled(false);//上拉加载-不可以
        mXRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);//设置下拉刷新的样式
        mXRecyclerView.addItemDecoration(myItemDecoration);
        mXRecyclerView.setAdapter(mAdapter);
        mXRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
//                new Handler().postDelayed(() -> {
//                    http_getData();
//
//                    int size = datas.size();
//                    datas.clear();
//                    for (int i = 0; i < 20; i++) {
//                        FogZoneListItemBean bean = new FogZoneListItemBean();
//                        bean.setWqbm("new" + i + "");
//                        bean.setGxsj("new" + "2011-11-11 11:12---" + i);
//                        bean.setWqmc("new" + "长江路雾区" + i);
//                        bean.setNjddj("new" + i + "");
//                        bean.setNjd(i);
//                        bean.setWqtq("new" + "良好" + i);
//                        datas.add(bean);
//                    }
//
//                    mAdapter.notifyDataSetChanged();
//                    mXRecyclerView.refreshComplete();
//                }, 2000);
            }

            @Override
            public void onLoadMore() {
//                http_getData();
//                mXRecyclerView.loadMoreComplete();//停止加载更多了
            }
        });
        //http_getData();




    }


    @Override
    public void resume() {
        super.resume();
        http_getData();

        registerRxbus();
    }


    private void registerRxbus(){
        Observable<Object> register = RxBus.getInstance().register(EquipmentDetailActivity.UPDATE_JCY);
        RxBus.getInstance().onEvent(register, obj -> {
            if (obj == null) return;
            setPushVisisblityInfo((String) obj);
        },throwable -> {
            registerRxbus();
        });
    }

    @Override
    protected void initWidget() {
        if (null != mCommonHeadRefreshView) {
            mCommonHeadRefreshView.setITimeRefresh(() -> http_refresh());
        }
        mAdapter.setOnItemClickListener(position -> {
            if (CommonUtils.isFastDoubleClick()) {
                return;
            }
            FogZoneListItemBean bean = datas.get(position);
            String wqbm = bean.getWqbm();//传递【雾区编码】的值
            //查询详情//传递3表示的是雾区详情页面
            EquipmentDetailActivity.startAction(mContext, ConstantsField.INDEX_3, bean);
        });
    }

    @Override
    protected void widgetClick(View v) {

    }

    /**
     * 请求数据
     */
    private void http_refresh() {
        http_getData();
    }

    @Override
    protected void initPrsenter() {
        mFPresenter.setView(this);
    }

    private void http_getData() {
        mFPresenter.http_getFogList(getActivity(), UserInfoUtils.getInstance().getToken(mContext));
    }

    @Override
    protected int setLayout() {
        return R.layout.layout_fragment_fogzone;
    }

    @Override
    public void onError(CommException e) {
        datas.clear();
        mAdapter.notifyDataSetChanged();
        if (TextUtils.isEmpty(e.getMessage())) {
            ToastUtil.showShort(mContext, mContext.getString(R.string.get_fogArea_list_error));
        } else
            ToastUtil.showShort(GlobalContext.context, e.getMessage());
    }

    @Override
    public void onResponse(List<FogZoneListItemBean> fogZoneListItemBeans) {
        //数据本地存储
        Gson gson = new Gson();
        String json = gson.toJson(fogZoneListItemBeans);
        SPUtils.saveStringData(mContext, ConstantsValue.JSON_DATA, json);
        Log.e(TAG, "onResponse: json====" + json);
        datas.clear();
        datas.addAll(fogZoneListItemBeans);
        mAdapter.notifyDataSetChanged();
        mCommonHeadRefreshView.refreshData(TimeUtils.getCurrentTime());
    }

    private void checkItem(PushVisibilityBean pushVisibilityBean) {
        if (datas == null || datas.size() == 0) return;

        int size = datas.size();
        String pushBm = String.valueOf(pushVisibilityBean.getWqbm());
        for (int i = 0; i < size; i++) {
            FogZoneListItemBean fogZoneListItemBean = datas.get(i);
            if (TextUtils.equals(fogZoneListItemBean.getWqbm(), pushBm)) {
                fogZoneListItemBean.setLmzt(pushVisibilityBean.getWqtq());
                fogZoneListItemBean.setNjddj(String.valueOf(pushVisibilityBean.getNjddj()));
                fogZoneListItemBean.setNjd(pushVisibilityBean.getNjd());
                break;
            }
        }
        mAdapter.notifyDataSetChanged();
    }


    private void setPushVisisblityInfo(String jsonMessage) {
        if (TextUtils.isEmpty(jsonMessage)) return;

        Gson gson = new Gson();
        FogZoneListItemBean detailBean = gson.fromJson(jsonMessage, FogZoneListItemBean.class);
        if (mAdapter != null && datas.size() > 0 && detailBean != null)
            for (int i = 0; i < datas.size(); i++) {
                if (datas.get(i).getWqbm().equals(detailBean.getWqbm())) {
                    datas.set(i, detailBean);

                    int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                    int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                    if (i - firstVisibleItemPosition >= 0 && i <= lastVisibleItemPosition) {
                        mAdapter.notifyItemChanged(i);
                    }
                    return;
                }
            }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getInstance().unRegister(EquipmentDetailActivity.UPDATE_JCY);
    }
}
